<template>
  <el-card class="app-container">
    <el-form :inline="true" :model="userInfo" class="demo-form-inline">
      <el-form-item>
        <el-input size="small" v-model="userInfo.user" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="search">查询</el-button>
        <el-button size="small" @click="reset">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button size="small" type="primary" @click="add">添加</el-button>
    <el-button size="small" type="danger" @click="deleteUsers" :disabled="checkArr.length == 0" >批量删除</el-button>
    <!-- 列表 
    tooltip-effect="dark"  hover高亮效果
    -->
    <el-table border :data="tableData" tooltip-effect="dark"
      style="width: 100%;margin: 20px 0;" @selection-change="checkArrChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="序号" width="80" type="index">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="150">
      </el-table-column>
      <el-table-column prop="roleName" label="角色列表" width="150">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间">
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间">
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="250">
        <template slot-scope="{row,index,column}">
          <el-button size="mini" type="success" @click="setPerson(row)">设置</el-button>
          <el-button size="mini" type="primary" @click="editUser(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="daleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination @size-change="setpageSize" @current-change="setPage" :current-page.sync="page"
      :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="prev, pager, next, jumper,->,sizes" :total="total">
    </el-pagination>
    <!-- 对话框 -->
    <el-dialog :title="form.id ? '修改用户' : '添加用户'" :visible.sync="dialogShow">
      <el-form ref="addForm" :model="form" :rules="rules">
        <el-form-item label="用户名" :label-width="'120px'" prop="name">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" :label-width="'120px'">
          <el-input v-model="form.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="!form.id" prop="password" label="用户密码" :label-width="'120px'">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 设置角色 -->
    <el-dialog title="设置角色" :visible.sync="showDialog">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="form.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="params.isIndeterminate" v-model="params.checkAll"
            @change="checkAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="params.userRoleIds" @change="checkedChange">
            <el-checkbox v-for="role in params.allRoles" :key="role.id" :label="role.id">{{ role.roleName
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </template>
    </el-dialog>     
  </el-card>
</template>

<script>
import { getUserList,addOrUpdateUser,removeUser,getUserPersonList,addUserPerson,removeUserArr } from '@/api/acl/user'
export default {
  data() {
    return {
      // 搜索数据
      userInfo: {
        user: '',
      },
      // 总条数
      total: 0,
      // 表格数据
      tableData: [],
      // 选中项数组
      checkArr: [],
      // 当前页
      page: 1,
      // 条数
      pageSize: 5,
      // 对话框显示
      dialogShow: false,
      form: {
        username: '',
        nickName: '',
        password: ''
      },
      showDialog: false,
      params: {
        checkAll: false,
        isIndeterminate: false,
        // 选中项
        userRoleIds: [],
        // 用户角色数组
        allRoles: []
      },
      // 表单校验
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
      }
    }
  },
  //方法
  methods: {
    async getUserInfo(page = this.page, pageSize = this.pageSize, searchParams) {
      const result = await getUserList(page, pageSize, {
        username: searchParams
      })
      this.tableData = result.data.items
      this.total = result.data.total
    },
    // 分配角色
    setPerson(row) {
      Object.assign(this.form, row)
      this.showDialog = true
      this.getRoles()
    },
    // 获取用户的角色列表
    async getRoles() {
      const result = await getUserPersonList(this.params.id)
      const { allRolesList, setPerson } = result.data
      this.params.allRoles = allRolesList
      this.params.userRoleIds = [...setPerson]
      this.params.checkAll = allRolesList.length === setPerson.length
      this.params.isIndeterminate = setPerson.length > 0 && setPerson.length < allRolesList.length
    },
    // 重置角色
    resetRoleData() {
      this.showDialog = false
      Object.assign(this.params, {
        allRoles: [],
        userRoleIds: [],
        isIndeterminate: false,
        checkAll: false
      })
    },
    // 全选的回调
    checkAllChange(val) {
      this.params.userRoleIds = val
        ? this.params.allRoles.map((item) => item.id)
        : []
      this.params.isIndeterminate = false
    },
    // 单选的回调
    checkedChange() {
      const { userRoleIds, allRoles } = this.params
      this.params.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
      this.params.isIndeterminate = userRoleIds.length > 0 && userRoleIds.length < allRoles.length
    },
    // 保存角色
    async save() {
      const userId = this.form.id
      const roleIds = this.params.userRoleIds.join(',')
      await addUserPerson(userId, roleIds)
      alert('分配角色成功')
      this.getUserInfo()
      this.resetRoleData()
    },
    // 搜索
    search() {
      this.getUserInfo(1, this.pageSize, this.userInfo.user)
    },
    // 清空
    reset() {
      this.userInfo.user = ''
      this.getUserInfo(1)
    },
    // 编辑用户
    editUser(row) {
      this.dialogShow = true
      Object.assign(this.form, row)
    },
    // 添加用户
    add() {
      // 清除表单
      this.form = {
        username: '',
        nickName: '',
        password: ''
      }
      this.dialogShow = true
      // 清空上依次输入
      this.$nextTick(() => {
        this.$refs.addForm.clearValidate()
      })
    },
    // 点击保存添加或更新
    async confirm() {
      if (!this.$refs.addForm.validate()) {
        alert('请输入正确内容')
        return
      }
      try {
        await addOrUpdateUser(this.form)
        alert('保存成功')
        // 清除表单
        this.form = {
          username: '',
          nickName: '',
          password: ''
        }
        // 更新页面
        this.getUserInfo(this.form.id ? this.page : 1)
        this.dialogShow = false
      } catch (error) {
        alert('保存失败')
        this.dialogShow = false
      }

    },
    // 删除某个用户
    async daleteUser(row) {
      await removeUser(row.id)
      alert('删除成功')
      this.getUserInfo()
    },
    //批量删除用户
    async deleteUsers(){
      try{
        await removeUserArr(this.checkArr)
        alert('删除成功')
        this.getUserInfo()
      }catch{
        alert('删除失败')
      }
    },
    // 多选回调
    checkArrChange(val) {
      this.checkArr = val.map(item => item.id)
    },
    // 改变条数回调
    setpageSize(val) {
      this.pageSize = val
      this.getUserInfo()
    },
    // 改变当前页回调
    setPage(val) {
      this.page = val
      this.getUserInfo()
    }
  },
  //生命周期钩子
  mounted() {
    this.getUserInfo()
  },
}
</script>

<style></style>